<?php


class SJB_Admin_I18n_ManagePhrases extends SJB_Function
{
	private static $phrases;

	public function isAccessible()
	{
		$this->setPermissionLabel('translate_phrases');
		return parent::isAccessible();
	}

	public function execute()
	{
		$errors = array();
		$result = '';
		$items_per_page = SJB_Request::getVar('phrases_per_page', 50);
		$template_processor = SJB_System::getTemplateProcessor();
		$page = SJB_Request::getVar('page', 1);
		$found_phrases = '';

		if (isset($_REQUEST['action'])) {
			$action_name = $_REQUEST['action'];
			$params = $_REQUEST;

			$action = SJB_PhraseActionFactory::get($action_name, $params, $template_processor);
			if ($action->canPerform()) {
				$action->perform();
				$result = isset($_REQUEST['result']) ? $_REQUEST['result'] : $action->result;

				/*pagination*/
				$total = $this->getPhrasesCount();
				if (empty($items_per_page)) {
					$items_per_page = $total;
					$found_phrases = self::$phrases;
				} else {
					$found_phrases = $this->getPhrasesByPage($page, $items_per_page);
				}

				$pages = array();
				for ($i = $page - 3; $i < $page + 3; $i++) {
					if ($i > 0)
						$pages[] = $i;
					if ($i * $items_per_page >= $total)
						break;
				}

				$totalPages = ceil($total / $items_per_page);
				if (empty($totalPages))
					$totalPages = 1;

				if (array_search(1, $pages) === false)
					array_unshift($pages, 1);
				if (array_search($totalPages, $pages) === false)
					array_push($pages, $totalPages);

				$template_processor->assign("totalPages", $totalPages);
				$template_processor->assign("pages", $pages);
				$template_processor->assign("totalPhrase", $total);
			}
			else {
				$errors = $action->getErrors();
			}
		}
		else {
			$template_processor->assign('criteria', $_REQUEST);
		}

		$i18n = SJB_ObjectMother::createI18N();

		$domains = $i18n->getDomainsData();
		$languages = $i18n->getLanguagesData();

		$template_processor->assign('result', $result);
		$template_processor->assign('domains', $domains);
		$template_processor->assign('languages', $languages);
		$template_processor->assign('errors', $errors);
		$template_processor->assign('phrases_per_page', $items_per_page);
		$template_processor->assign("currentPage", $page);
		$template_processor->assign('found_phrases', $found_phrases);
		$template_processor->display('manage_phrases.tpl');
	}

	public static function setPhrases($phrases)
	{
		self::$phrases = $phrases;
	}

	public function getPhrasesCount()
	{
		return count(self::$phrases);
	}

	private static function getPhrasesByPage($page, $items_per_page)
	{
		$end = $page * $items_per_page;
		$begin = $end - $items_per_page;
		if ($end > count(self::$phrases)) {
			$end = $end - ($end - count(self::$phrases));
		}
		$found_phrases = '';
		for ($i = $begin; $i <= $end - 1; $i++) {
			$found_phrases[$i] = self::$phrases[$i];
		}
		return $found_phrases;
	}
}
